<!-- 项目展示列表页面 -->
<template>
  <view class="min-h-screen bg-gray-50">
    <view class="max-w-[750rpx] mx-auto sticky top-0 z-[2]">
      <!-- 头部区域 -->
      <PageHeader title="项目展示" :showBack="true" :onlyBack="true"/>
      <view
        class="bg-gradient-to-r from-[#165DFF] to-[#1890ff] sticky top-0 z-[2] text-white px-[32rpx] pt-[100rpx] pb-[20rpx] rounded-b-[32rpx] mb-[-40rpx] relative shadow-md"
      >
        <!-- 搜索组件 -->
        <SearchView @search="handleSearch" placeholder="搜索项目名称或描述..." />
      </view>
    </view>

    <!-- 项目列表 -->
    <view class="px-6 mt-[60rpx]">
      <!-- 加载状态 -->
      <view v-if="loading" class="flex items-center justify-center py-20">
        <IconFont name="loading" size="48rpx" class="animate-spin text-blue-600 mr-4" />
        <text class="text-[28rpx] text-gray-600">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="filteredProjects.length === 0" class="flex flex-col items-center justify-center py-20">
        <IconFont name="empty" size="120rpx" class="text-gray-300 mb-6" />
        <text class="text-[32rpx] font-medium text-gray-500 mb-2">{{ searchKeyword ? '未找到相关项目' : '暂无项目展示' }}</text>
        <!-- <text class="text-[24rpx] text-gray-400 mb-8">{{ searchKeyword ? '请尝试其他关键词' : '点击右上角添加第一个项目' }}</text> -->
        <!-- <nut-button 
          v-if="!searchKeyword"
          type="primary" 
          size="large"
          @click="handleAdd"
        >
          添加项目
        </nut-button> -->
      </view>

      <!-- 项目列表 -->
      <view v-else class="space-y-4">
        <view 
          v-for="project in filteredProjects" 
          :key="project.id"
          class="bg-white rounded-[24rpx] shadow-sm overflow-hidden mb-4 hover:shadow-md transition-all duration-300 cursor-pointer"
          @click="handleViewDetails(project)"
        >
          <view class="flex p-[20rpx]">
            <!-- 左侧图片 -->
            <view class="relative w-[200rpx] h-[160rpx] rounded-[16rpx] overflow-hidden flex-shrink-0 mr-4">
              <image 
                :src="getImageList(project.pics)[0] || 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'" 
                class="w-full h-full object-cover"
                mode="aspectFill"
              />
              
              
            </view>

            <!-- 右侧内容 -->
            <view class="flex-1 flex flex-col justify-between">
              <!-- 标题和描述 -->
              <view class="flex-1">
                <view class="mb-2">
                  <text class="text-[28rpx] font-bold text-gray-900 line-clamp-2 leading-[1.4]">{{ project.title }}</text>
                </view>
                
                <view class="mb-3">
                  <text class="text-[24rpx] text-gray-600 line-clamp-2 leading-[1.4]">{{ project.content }}</text>
                </view>

                <view class="mb-2 text-[20rpx] text-gray-500">
                  发布方：{{ project.contact }}
                </view>

                <!-- 服务区域 -->
                <!-- <view v-if="project.address" class="mb-2">
                  <view class="flex items-center">
                    <IconFont name="location" size="20rpx" class="text-gray-400 mr-1" />
                    <text class="text-[22rpx] text-gray-500">{{ project.address }}</text>
                  </view>
                </view> -->

                <!-- 状态标签 -->
                <!-- <view class="mb-2">
                  <view 
                    class="inline-block px-2 py-1 rounded-[8rpx] text-[20rpx] font-medium"
                    :class="project.status === 1 ? 'bg-green-100 text-green-600' : 'bg-gray-100 text-gray-600'"
                  >
                    {{ getStatusText(project.status) }}
                  </view>
                </view> -->
              </view>

              <!-- 底部信息 -->
              <view class="flex items-center justify-between">
                
                <view 
                :class="getLevelStyle(project.plevel)"
                class="px-2 py-[3rpx] rounded-[4rpx] text-[18rpx] font-medium border border-solid"

                  v-if="project.plevel > 4"
                >
                  {{ getLevelText(project.plevel) }}
                </view>
           
                <!-- 发布时间 -->
                <view class="flex items-center">
                  <!-- <IconFont name="time" size="20rpx" class="text-gray-400 mr-1" />
                  <text class="text-[20rpx] text-gray-400">{{ formatDate(project.create_time) }}</text> -->
                </view>
                
                <!-- 浏览量 -->
                <view class="flex items-center">
                  <!-- <IconFont name="eye" size="20rpx" class="text-gray-400 mr-1" /> -->
                  <text class="text-[20rpx] text-gray-400">{{ project.create_time || '-' }}</text>
                </view>
              </view>
            </view>

          </view>
        </view>
        
        <!-- 加载更多按钮 -->
        <view v-if="filteredProjects.length > 0" class="flex justify-center mt-[20rpx]">
          <nut-button 
            size="normal" 
            type="primary" 
            :loading="isLoading" 
            :disabled="isLoading || noMore" 
            @click="loadMore" 
            class="w-[300rpx]"
          >
            {{ noMore ? "没有更多了" : "加载更多" }}
          </nut-button>
        </view>
      </view>
    </view>

    <!-- 添加项目按钮 -->
    <!-- <view class="fixed bottom-6 right-6">
      <view 
        class="w-[120rpx] h-[120rpx] bg-blue-600 rounded-full flex items-center justify-center shadow-lg cursor-pointer"
        @click="handleAdd"
      >
        <IconFont name="add" size="48rpx" class="text-white" />
      </view>
    </view> -->
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'
import Taro from '@tarojs/taro'
import PageHeader from '@/components/PageHeader.vue'
import SearchView from '@/components/SearchView.vue'
import { post } from '@/utils/request'

/**
 * 项目数据类型定义
 */
interface Project {
  id: number
  title: string
  content: string
  pics: string
  status: number
  rangeType: number
  create_time: string
  update_time: string
  plevel: number
  viewCount?: number
  address?: string,
  releaseStatus?: number,//发布状态，任务类：1 待支付 2 审核中 3 审核通过 4 审核不过 5 已结束
}

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const projects = ref<Project[]>([])

// 分页相关
const pageNo = ref(1)
const pageSize = ref(10)
const isLoading = ref(false)
const noMore = ref(false)

/**
 * 过滤后的项目列表（现在通过API搜索，直接返回项目列表）
 */
const filteredProjects = computed(() => {
  return projects.value
})

/**
 * 处理搜索
 */
const handleSearch = (keyword: string) => {
  searchKeyword.value = keyword
  resetPagination()
  loadProjects()
}

/**
 * 重置分页参数
 */
const resetPagination = () => {
  pageNo.value = 1
  projects.value = []
  noMore.value = false
}

/**
 * 获取图片列表
 * @param pics 图片字符串，用逗号分隔
 */
const getImageList = (pics: string) => {
  if (!pics) return ['http://www.dzgktf.com/templets/default/images/wtyt.jpg']
  const images = pics.split(',').filter(pic => pic.trim())
  return images.length > 0 ? images : ['http://www.dzgktf.com/templets/default/images/wtyt.jpg']
}

/**
 * 获取状态文本
 * @param status 状态值
 */
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    // 0: '草稿',
    // 1: '已发布',
    // 2: '已下架',
    // 3: '已删除'
    // 1 待支付 2 审核中 3 审核通过 4 审核不过 5 已结束
    1: '待支付',
    2: '审核中',
    3: '审核通过',
    4: '审核不过',
    5: '已结束'
  }
  return statusMap[status] || '未知'
}

const getLevelText = (level: number) => {
  const levelMap: { [key: number]: string } = {
    5: '普通项目',
    6: '平台推荐项目',
    7: '战略合作项目',
  }
  return levelMap[level] || '未知'
}

/**
 * 获取等级样式
 */
const getLevelStyle = (level: number) => {
  const levelStyles: { [key: number]: string } = {
    5: `border-orange-300 text-orange-300`, // 蓝色 - 普通项目
    6: `border-orange-600 text-orange-600`, // 橙色 - 平台项目  
    7: `border-red-600 text-red-600`, // 红色 - 战略项目
  }
  
  return levelStyles[level] || `border-orange-300 text-orange-300` // 默认蓝色
}

/**
 * 获取范围类型文本
 * @param rangeType 范围类型
 */
const getRangeTypeText = (rangeType: number) => {
  const rangeMap: { [key: number]: string } = {
    0: '全国',
    1: '省级',
    2: '市级'
  }
  return rangeMap[rangeType] || '未知'
}

/**
 * 格式化日期
 */
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
  }
  
  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }
  
  // 小于7天
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
  
  // 超过7天显示具体日期
  return date.toLocaleDateString()
}

/**
 * 添加项目
 */
const handleAdd = () => {
  Taro.navigateTo({
    url: '/pages/project-show/edit'
  })
}

/**
 * 查看详情
 */
const handleViewDetails = async (project: Project) => {
  try {
    // 调用接口获取项目详情
    const res = await post('/groupTypes/getById', { id: project.id })
    
    if (res.code === 0 && res.data) {
      // 将详情数据存储到全局状态或传递给页面
      Taro.setStorageSync('projectDetail', res.data)
      
      // 跳转到预览页面
      Taro.navigateTo({
        url: `/pages/project-show/preview?id=${project.id}`
      })
    } else {
      Taro.showToast({
        title: res.message || '获取详情失败',
        icon: 'error',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    Taro.showToast({
      title: '获取详情失败，请重试',
      icon: 'error',
      duration: 2000
    })
  }
}

/**
 * 编辑项目
 */
const handleEdit = async (project: Project) => {
  try {
    // 调用接口获取项目详情
    const res = await post('/groupTypes/getById', { id: project.id })
    
    if (res.code === 0 && res.data) {
      // 将详情数据存储到全局状态或传递给页面
      Taro.setStorageSync('projectDetail', res.data)
      
      // 跳转到编辑页面
      Taro.navigateTo({
        url: `/pages/project-show/edit?id=${project.id}`
      })
    } else {
      Taro.showToast({
        title: res.message || '获取详情失败',
        icon: 'error',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    Taro.showToast({
      title: '获取详情失败，请重试',
      icon: 'error',
      duration: 2000
    })
  }
}

/**
 * 删除项目
 */
const handleDelete = async (project: Project) => {
  Taro.showModal({
    title: '确认删除',
    content: `确定要删除项目"${project.title}"吗？删除后无法恢复。`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用删除接口
          const deleteRes = await post('/groupTypes/updateStatus', {
            id: project.id,
            status: 3 // 删除状态
          })
          
          if (deleteRes.code === 0) {
            // 从本地列表中移除
            const index = projects.value.findIndex(p => p.id === project.id)
            if (index > -1) {
              projects.value.splice(index, 1)
            }
            
            Taro.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1500
            })
          } else {
            Taro.showToast({
              title: deleteRes.message || '删除失败',
              icon: 'error',
              duration: 2000
            })
          }
        } catch (error) {
          console.error('删除项目失败:', error)
          Taro.showToast({
            title: '删除失败，请重试',
            icon: 'error',
            duration: 2000
          })
        }
      }
    }
  })
}

/**
 * 加载项目列表
 */
const loadProjects = async (isLoadMore = false) => {
  isLoading.value = true
  
  try {
    const params: any = {
      pageNo: pageNo.value,
      pageSize: pageSize.value
    }
    
    // 如果有搜索关键词，添加到参数中
    if (searchKeyword.value) {
      params.title = searchKeyword.value
    }
    
    const res = await post('/groupTypes/all', params)
    
    console.log('项目展示列表数据 === 》', res)
    
    if (res.code === 0 && res.data) {
      const newProjects = res.data.map((item: any) => ({
        ...item.columns,
        id: item.columns.id,
        title: item.columns.title,
        content: item.columns.content,
        pics: item.columns.pics,
        status: item.columns.status,
        rangeType: item.columns.rangeType,
        create_time: item.columns.create_time,
        update_time: item.columns.update_time,
        plevel: item.columns.plevel || 5, // 添加 plevel 属性，默认为 5
        viewCount: Math.floor(Math.random() * 1000) // 模拟浏览量
      }))
      
      // 第一页直接赋值，后续页追加数据
      if (pageNo.value === 1) {
        projects.value = newProjects
      } else {
        projects.value = [...projects.value, ...newProjects]
      }
      
      // 判断是否还有更多数据（当前页数据小于pageSize则说明没有更多）
      noMore.value = newProjects.length < pageSize.value
    }
  } catch (error) {
    console.error('加载项目列表失败:', error)
    Taro.showToast({
      title: '加载失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    isLoading.value = false
  }
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (isLoading.value || noMore.value) return
  pageNo.value++ // 页码+1
  loadProjects()
}

// 页面加载时获取数据
onMounted(() => {
  loadProjects()
})
</script>
